import {
  addFrameIfNotExsit,
  addFrameListener,
  executeFunctionFromIframe,
  getCallCenterIframe
} from "@/utils/callcenter/base/CallCenterRpc";


export class ChinaUnicomSDK {
  context = null;
  eventMap = {
    "sessionTerminate": "EVENT_CALL_TERMINATED",
    "previewOutcallBridge": "EVENT_CALL_CONNECTED",
    "previewOutcallStart": "EVENT_CALL_INCOMING",
  };
  eventDic = {};

  constructor(url) {

    addFrameIfNotExsit("TiNetSDKFrame", url);
    this.context = getCallCenterIframe("TiNetSDKFrame");
    if (this.context) {
      this.context.location = url;
    }
  }

  /**
   * 拿token 执行JS登录到系统中
   * @param token
   */
  login = (token) => {

  }

  /**
   * 1.录音确认
   * 2.录音加载
   * 3.回拨的电话拾取
   */
  init = () => {

    addFrameListener("TiNetEvent", (event) => {
        console.log(event);
        if (event) {
          const eventJson = JSON.parse(event);
          let type = this.eventMap[eventJson.eventType];
          if (type != null) {
            let func = this.eventDic[type];
            if (func) {
              func(event);
            }
          }

        }
      }
    );
  }

  /**
   * 取消拨打的电话
   */
  cancelCall = () => {
    executeFunctionFromIframe(this.context, "cancelCall", null, data => {
      console.log(data)
    })
  }

  /**
   * 拨打电话 并且生成拨打记录
   * @param bizId
   * @param number
   */
  makeCall = (bizId, number, callRegistno, callAcntName, callAcntCode, callAcntTypeCode, calledName) => {
    let obj = {
      tel: number,
      callAcntName: callAcntName,
      callAcntCode: callAcntCode,
      calledName: calledName,
      callBizid: bizId,
      callRegistno: callRegistno,
      createAccountTypeCode: callAcntTypeCode,
    };
    executeFunctionFromIframe(this.context, "makeCall", obj, (data) => {
      console.log("callback", data);
    });
  };

  addEventListener = (name, handler) => {
    this.eventDic[name] = handler;
  }

}
